// pages/player/player.js
const backgroundAudioManager = wx.getBackgroundAudioManager()
let musiclist = []
let nowPlayingIndex = 0
const app = getApp()

const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    songDetail: {},
    isPlaying: false,
    showLyric: false,
    lyric: '',
    // 是否播放同一首歌曲
    isSame: false,
    touchStart: {
      x: 0,
      y: 0
    },
    touchEnd: {
      x: 0,
      y: 0
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(options.musicId)
    // 获取 musiclist 组件传递过来数据
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', (data) => {
      // console.log(data.data)
      nowPlayingIndex = data.data.index
    })


    // 获取缓存中歌单数据
    musiclist = wx.getStorageSync('musiclist')

    this._loadMusicDetail(options.musicId)


  },
  _loadMusicDetail(musicId) {
    if (musicId == app.getPlayingMusicId()) {
      this.setData({
        isSame: true
      })

    } else {
      this.setData({
        isSame: false
      })
    }
    if (!this.data.isSame) {
      backgroundAudioManager.stop()
      this._beforeLoadData()
    }

    wx.cloud.callFunction({
      name: 'getMusic',
      data: {
        musicId,
        $url: 'musicUrl',

      }
    }).then((res) => {
      if (res.result.data[0].url == null) {
        wx.showToast({
          title: '该歌曲暂无资源',
        })
        return
      }
      this.setData({
        songDetail: musiclist[nowPlayingIndex].al
      })
      // 设置tab栏为歌曲名
      wx.setNavigationBarTitle({
        title: musiclist[nowPlayingIndex].name + '(' + musiclist[nowPlayingIndex].ar[0].name + ')'
      })



      // 全局设置当前播放音乐id
      app.setPlayMusicId(musicId)
      // console.log(res.result)
      const songInfo = res.result.data[0]

      if (!this.data.isSame) {
        backgroundAudioManager.src = songInfo.url
        backgroundAudioManager.title = musiclist[nowPlayingIndex].name
        backgroundAudioManager.coverImgUrl = this.data.songDetail.picUrl
        backgroundAudioManager.singer = musiclist[nowPlayingIndex].ar[0].name
        // 专辑名称
        backgroundAudioManager.epname = musiclist[nowPlayingIndex].al.name
        // 保存播放历史
        this.savePlayHistory()
      }
      this._playSong()
      this._requestLyric(musicId)


      wx.hideLoading()

    })
  },
  _requestLyric(musicId) {
    // 加载歌词
    wx.cloud.callFunction({
      name: 'getMusic',
      data: {
        musicId,
        $url: 'lyric',
      }
    }).then((res) => {
      // console.log(res)
      this.setData({
        lyric: res.result.lrc ? res.result.lrc.lyric : '暂无歌词'
      })

    })
  },
  _playSong() {
    this.setData({
      isPlaying: true
    })
  },
  _pauseSong() {
    this.setData({
      isPlaying: false
    })
  },
  _beforeLoadData() {
    wx.showLoading({
      title: '正在加载数据',
    })
  },
  togglePlay() {
    if (this.data.isPlaying) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }

    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  onPrev() {
    nowPlayingIndex--
    if (nowPlayingIndex < 0) {
      nowPlayingIndex = musiclist.length - 1
    }
    this._loadMusicDetail(musiclist[nowPlayingIndex].id)
  },
  onNext() {
    nowPlayingIndex++
    if (nowPlayingIndex === musiclist.length) {
      nowPlayingIndex = 0
    }
    this._loadMusicDetail(musiclist[nowPlayingIndex].id)
  },
  onChangeLyric() {
    this.setData({
      showLyric: !this.data.showLyric
    })
  },
  // 联动歌词, process-bar 传递过来事件
  timeUpdate(event) {
    // 选取组件
    this.selectComponent('.lyric').update(event.detail.currentTime)
  },
  touchStart(e) {
    this.setData({
      ['touchStart.x']: e.changedTouches[0].clientX,
      ['touchStart.y']: e.changedTouches[0].clientY
    });
  },
  touchEnd(e) {
    this.setData({
      ['touchEnd.x']: e.changedTouches[0].clientX,
      ['touchEnd.y']: e.changedTouches[0].clientY
    });
    console.log(this.data.touchEnd.x, this.data.touchEnd.x)
    // endX, endY, startX, startY
    // this.data.touchEnd.x, this.data.touchEnd.x,this.data.touchStart.x,this.data.touchStart.y
    let getTouchData = util.getTouchData(this.data.touchEnd.x, this.data.touchEnd.y, this.data.touchStart.x, this.data.touchStart.y)
    if (getTouchData == "right"){
      console.log('左')
      this.onPrev()
    } else if (getTouchData == "left"){
      this.onNext()
      console.log('右')
    }else{
      console.log('nothing')
    }
    // this.setData({
    //   ['touchStart.x']: 0,
    //   ['touchStart.y']: 0,
    //   ['touchEnd.x']: 0,
    //   ['touchEnd.y']: 0
    // });
  },
  savePlayHistory(){
    // 当前正在播放歌曲对象
    const music = musiclist[nowPlayingIndex]
    const openID = app.globalData.openID
    console.log('save', openID)
    const history = wx.getStorageSync(openID)
    let bHave = false
    for(let i = 0, len = history.length; i < len; i++) {
      if(history[i].id == music.id){
        bHave = true
        break
      }
    }
    if(!bHave){
      history.unshift(music)
      wx.setStorage({
        key: openID,
        data: history,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log('page show')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})